#include "Inmultit.h"
#include "Plus.h"

long double Inmultit::calcul(long double aux1, long double aux2)
{
    return aux1 * aux2;
}

long double Inmultit::calcul()
{
    if (!fStang || !fDrept)
        exit(1);
    return calcul(fStang->calcul(), fDrept->calcul());
}

char *Inmultit::derivare()
{
    char *aux1, *aux11, *aux2, *aux22, *aux, *aux00, *aux01;

    if (!fStang || !fDrept)
        exit(1);

    aux1 = fStang->derivare();
    aux11 = fStang->toString();
    aux2 = fDrept->derivare();
    aux22 = fDrept->toString();

    aux00 = concatTermeni(aux1, aux22);
    aux01 = concatTermeni(aux2, aux11);
    aux = Plus::concatTermeni(aux00, aux01);

    delete aux1; delete aux2; delete aux11; delete aux22; delete aux00; delete aux01;
    return aux;
}

long double Inmultit::calculDerivata()
{
    if (!fStang || !fDrept)
        exit(1);

    return Plus::calcul(calcul(fStang->calculDerivata(), fDrept->calcul()),
            calcul(fDrept->calculDerivata(), fStang->calcul()));
}

char *Inmultit::toString()
{
    char *aux1, *aux2, *aux;

    if (!fStang || !fDrept)
        exit(1);

    aux1 = fStang->toString();
    aux2 = fDrept->toString();

    aux = concatTermeni(aux1, aux2);
    delete aux1; delete aux2;

    return aux;
}

char *Inmultit::concatTermeni(char *aux1, char *aux2)
{
    char *aux;

    if (!strcmp(aux1, "0") || !strcmp(aux2, "0"))
        aux = cpystr((char*)"0");
    else if (!strcmp(aux1, "1")) aux = cpystr(aux2);
    else if (!strcmp(aux2, "1")) aux = cpystr(aux1);
    else
    {
        aux = new char[strlen(aux1) + strlen(aux2) + 4];
        strcpy(aux, "(");
        strcat(aux, aux1); strcat(aux, "*"); strcat(aux, aux2); strcat(aux, ")");
    }
    return aux;
}
